'use strict'

let {Sequelize, DataTypes } = require('sequelize');
const {database, username, password, host, dialect } = require('./config');

//实例化Sequelize(连接数据库)
let sequelize = new Sequelize(database, username, password, {
    host: host,
    dialect: dialect
});

//用方法统一模型定义
function defineModel(name, attrs) {
    //定义一个新的对象相当于一个表格
    let prop = {};

    //定义属性
    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
    };
    //循环定义属性
    for (let key in attrs) {
        prop[key] = attrs[key];
    };
    prop.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };
    prop.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    };
    prop.version = {
        type: DataTypes.INTEGER,
        allowNull: false
    };
    prop.remarks = {
        type:DataTypes.STRING(800),
        allowNull: true
    };

    //模型定义
    let User = sequelize.define(name, prop, {
        tableName: name,
        timestamps: false,

        //定义钩子
        hooks: {
            //在对数据表插入数据需要验证前表执行的判断
            beforeValidate: function (obj) {
                //生成一个时间戳
                let no = Date.now();
                // 如果是新插入数据，则创建时间和更新时间一样，并且版本设置为0；如果是更新数据，则更新时间重新赋值，并对版本自增1
                if (obj.isNewRecord) {
                    obj.createdAt = no;
                    obj.updatedAt = no;
                    obj.version = 0;
                } else {
                    obj.updatedAt = no;
                    obj.version += 1;
                }
            }
        }
    });
    return User;
};

let obj={
    sequelize,
    defineModel,
    DataTypes
};
//暴露Sequelize实例、模型定义方法、数据类型
module.exports=obj;

